package com.huika.renrench.utils;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.config.Constant;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.login.event.LoginEvent;
import com.huika.renrench.control.login.event.LogoutEvent;
import com.huika.renrench.control.main.activity.MainActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.http.ServerFlagError;
import com.huika.renrench.http.ServerJsonUnParseError;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.support.helps.VersionManager;

import de.greenrobot.event.EventBus;
/**
* @ClassName: LoginUtils 
* @说明: 登陆帮助类
* @author zwy
* @date 2015年6月15日 上午9:53:46
 */
public class LoginUtils {
	private Context context;
	private String pwd;
	private String userName;
	
	public LoginUtils(Context context) {
		super();
		this.context = context;
	}
	
	/**
	 * @说明:登陆
	 * @author: zwy
	 */
	public void login(String userName, String pwd){
		loginNet(userName, MD5Security.getMd5_32_UP(pwd));
	}
	/**
	 * @说明:自动登陆
	 * @author: zwy
	 */
	public void autoLogin(){
		String userName = PreferencesHelper.getString(PreferencesHelper.KEY_LOGIN_NAME);
		String pwd = PreferencesHelper.getString(PreferencesHelper.KEY_LOGIN_PWD);
		if (userName!=null && !TextUtils.isEmpty(userName) && pwd !=null && !TextUtils.isEmpty(pwd)) {
			loginNet(userName, pwd);
		}
	}
	/**
	 * @说明:判断是否登陆
	 * @author: zwy
	 */
	public static boolean isLogin(){
		return GlobalApp.userModel==null?false:true;
	}
	/**
	 * @说明:
	 * @author: zwy
	 */
	public static void logout(){
		GlobalApp.userModel = null;
		PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_PWD,"");
		EventBus.getDefault().post(new LogoutEvent(1));
	}

	private void loginNet(String userName, String pwd) {
		this.userName = userName;
		this.pwd = pwd;
		FormResultRequest<UserModel> request = new FormResultRequest<UserModel>(UrlConstants.LOGINVALIDATEFORUSERAPP, listener, errorListener,
				new TypeToken<RequestResult<UserModel>>() {
				}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putStringTypeParam("userName", userName);
		ajaxParams.putStringTypeParam("password", pwd);
		ajaxParams.putStringTypeParam("ip", GlobalApp.getIp());
		ajaxParams.putStringTypeParam("mac", GlobalApp.mac);
		ajaxParams.putStringTypeParam("dev", Constant.DEV);
		request.setRequestParams(ajaxParams);
		VolleyRequestManager.addRequest(request, this);
	}

	private Listener<RequestResult<UserModel>> listener = new Listener<RequestResult<UserModel>>() {
		@Override
		public void onResponse(RequestResult<UserModel> arg0) {
			UserModel userModel = arg0.getRs();
			if (arg0.flag == 1 && userModel != null) {
				GlobalApp.userModel = userModel;
				PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_NAME,userName);
				PreferencesHelper.setString(PreferencesHelper.KEY_LOGIN_PWD,pwd);
				EventBus. getDefault().post(new LoginEvent(1,arg0.msg));
				
			} else {
				ToastMsg.showToastMsg(context, arg0.msg);
			}
		}
	};

	private ErrorListener errorListener = new ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			String msg = "网络异常";
			if (error instanceof ServerFlagError) {
				msg = ((ServerFlagError) error).result.msg;
			} else if (error instanceof ServerJsonUnParseError) {
				try {
					String res = ((ServerJsonUnParseError) error).result;
					JSONObject jsonObject = new JSONObject(res);
					msg = jsonObject.getString("msg");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				try {
					if (error.networkResponse != null
							&& error.networkResponse.data != null){
						msg = new String(error.networkResponse.data, "utf-8");
						if(TextUtils.isEmpty(msg)){
							msg = "未知异常";
						}
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			ToastMsg.showToastMsg(context,msg==null||TextUtils.isEmpty(msg)?"网络异常":msg);
			EventBus. getDefault().post(new LoginEvent(0,msg));
		}
	};
	
}
